package com.isyscore.os.etl.route;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.isyscore.device.common.model.RespDTO;
import com.isyscore.device.common.util.JsonMapper;
import com.isyscore.os.core.properties.RouteInfoProperties;
import com.isyscore.os.permission.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
@EnableConfigurationProperties(RouteInfoProperties.class)
public class RouteRegisterLifecycle implements SmartLifecycle {
    @Autowired
    private RouteInfoProperties routeInfoProperties;
    @Override
    public void start() {
        if(CollUtil.isNotEmpty(routeInfoProperties.getExcludeUrl())){
            Map<String,String> paramMap= Maps.newHashMap();
            paramMap.put("serviceId",routeInfoProperties.getServiceId());
            paramMap.put("excludeUrl", StrUtil.join(";",routeInfoProperties.getExcludeUrl()));
            try {
                HttpResponse response = HttpRequest.post(routeInfoProperties.getRouterService()+routeInfoProperties.getRefreshRoutePath())
                        .contentType("application/json")
                        .body(JsonMapper.toNonDefaultJson(paramMap))
                        .timeout(5000)
                        .execute();
                RespDTO respDTO= JSONObject.parseObject(response.body(), RespDTO.class);
                if (!response.isOk()|| respDTO.getCode()!=ErrorCode.OK.getCode()) {
                    log.error("刷新路由信息失败，状态码为：{},返回信息为：{}",response.getStatus(),respDTO.getMessage());
                }
            }catch (Exception e){
                log.error("刷新路由信息发生异常:{}",e.getMessage());
            }
        }
    }

    @Override
    public void stop() {

    }

    @Override
    public boolean isRunning() {
        return false;
    }
}
